package com.aliyun.miniappdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * LogPoint
 *
 * @author jiedu
 * @date 2024/07/16
 */
@Component
public class LogPoint implements CommandLineRunner {

    @Value("${app.manual-deploy:false}")
    private boolean isManualDeploy;

    private static final String BASE_ECS_URL = "http://100.100.100.200/latest/meta-data";

    private static final String BASE_LOG_URL = "https://aliyun-solution.cn-hangzhou.log.aliyuncs.com/logstores/aliyun-solution-demo/track?APIVersion=0.6.0";

    private final RestTemplate restTemplate;

    @Autowired
    public LogPoint(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public void run(String... strings) {
        try {
            if (!isManualDeploy) {
                return;
            }
            Map<String, String> params = new HashMap<>();
            params.put("solution", "tech_solu_103");
            params.put("detail-id", "2715331");
            params.put("instance-type", fetch("/instance/instance-type"));
            params.put("instance-name", fetch("/instance/instance-name"));
            params.put("eipv4", fetch("/eipv4"));
            params.put("region-id", fetch("/region-id"));
            params.put("zone-id", fetch("/zone-id"));
            params.put("owner-account-id", fetch("/owner-account-id"));
            params.put("image-id", fetch("/image-id"));
            String url = BASE_LOG_URL + "&" + toQueryString(params);
            restTemplate.getForObject(url, String.class);
        } catch (Exception ignored) {

        }
    }

    private String fetch(String path) {
        return restTemplate.getForObject(BASE_ECS_URL + path, String.class);
    }

    private String toQueryString(Map<String, String> params) {
        return params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
    }
}
